/*
Copyright (c) 2011, Jeffrey Kunkel
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions 
are met:

Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution.
Neither the name of the Jeffrey Kunkel nor the names of its contributors 
may be used to endorse or promote products derived from this software 
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MICROTHREAD_H_
#define MICROTHREAD_H_

#include "thread_group.hpp"
#include "ProducerConsumer.hpp"
#include <boost/function.hpp>

template< typename alloc >
void MicroThreadRunner( 
  ProduceConsume<boost::function0<void>, alloc> & que,
  boost::function1<void, void* > message_handler ) 
{
  boost::function0<void> f;
  while(1) {
    try {
      f = que.consume();
      f();
    } catch( void* msg ) {
      if( msg == 0 )
        return;
      if( message_handler )
        message_handler(msg);
    }
  }
}

struct is_my_thread {
  boost::thread::id id;
  inline is_my_thread() : id( boost::this_thread::get_id() ) {}
  inline bool operator()( boost::thread * t ) {
    return t->get_id() == id;
  }
};

template<
  typename alloc = std::allocator<boost::function0<void> >
>
class MicroThreadExecution 
  : public ProduceConsume<boost::function0<void>, alloc> {
public:
  struct remove_thread_functor {
    MicroThreadExecution<alloc> & mte;
    inline remove_thread_functor( MicroThreadExecution<alloc> & mte )
      : mte(mte) {}
    inline void operator()() {
      mte.delete_thread_if( is_my_thread(), false );
      throw (void*)NULL; 
    }
  };
private:
  boost::function1<void, void* > message_handler;
  const boost::function2<int,int,int> balance;
  jdkunk::thread_group runners;
public:
  /// Balance is given the number of threads and the number
  /// of requests. Balance returns a negative value for the
  /// number of threads to remove, and a positive number for
  /// the number of threads to add. The number returned is the
  /// number of threads which will be added/removed.
  MicroThreadExecution( 
    const int num_of_threads, 
    boost::function1<void, void* > message_handler = NULL,
    boost::function2<int,int,int> balance = NULL
  )
  : message_handler(message_handler)
  , balance(balance) 
  {
    for( int i = 0; i < num_of_threads; ++i ) {
      boost::thread * thread = new boost::thread(
        MicroThreadRunner<alloc>, 
        boost::ref< ProduceConsume<boost::function0<void>, alloc> >(*this),
        message_handler 
      );
      runners.add_thread( thread );
    }
  }
  inline ~MicroThreadExecution() {
    runners.interrupt_all();
  }
  inline void produce( const boost::function0<void> & f ) {
    assert( f != NULL && "The function must be valid." );
    ProduceConsume<boost::function0<void>, alloc>
      ::produce(f);

    if( balance != NULL ) {
      const int r = balance(
        runners.size(), 
        ProduceConsume<boost::function0<void>, alloc>::size() );
      if( r > 0 ) {
        for( int i = 0; i < r; ++i )
          add_thread();
        return;
      }
      if( r < 0 ) {
        for( int i = 0; i < std::max(1,-r); ++i )
          ProduceConsume<boost::function0<void>, alloc>
            ::produce_quickly( remove_thread_functor(*this) );
        return;
      }
    }
  }
  inline boost::thread * remove_thread( boost::thread * thread, bool replace = true ) {
    runners.remove_thread(thread);
    if(replace && thread) add_thread();
    return thread;
  }
  template< typename Predicate >
  inline void delete_thread_if( Predicate p, bool replace = true ) {
    boost::thread * thread = find_thread_if<Predicate>(p);
    if(thread) delete thread;
    if(replace) add_thread();
  }
  template< typename Predicate >
  inline boost::thread * find_thread_if( Predicate p ) {
    return runners.find_thread_if<Predicate>(p);
  }
  template< typename Predicate >
  inline void for_each_thread( Predicate p ) {
    runners.for_each_thread(p);
  }
  inline void add_thread() {
    boost::thread * thread = new boost::thread(
      MicroThreadRunner<alloc>, 
      boost::ref< ProduceConsume<boost::function0<void>, alloc> >(*this),
      message_handler 
    );
    runners.add_thread( thread );
  }
  inline void resize( const int n ) {
    if( n > runners.size() ) {
      for( int i = runners.size(); i != n; ++i ) 
        add_thread();
    } else if( n < runners.size() ) {
      for( int i = n; i != runners.size(); ++i ) 
        produce( remove_thread_functor(*this) );
    }
  }
  inline void join( ) {
    for( int i = 0; i != runners.size(); ++i ) 
      produce( remove_thread_functor(*this) );
    runners.join_all();
  }
};

#endif
